// const _ = require("underscore");
const cors = require("cors");
const express = require("express");
const app = express();
const http = require("http").createServer(app);
const io = require("socket.io")(http, { cors: true });
// const schedule = require("node-schedule");
const mdb = require("./mongodb/db");
const os = require("os");


///获取本机ip///
function getIPAdress() {
  var interfaces = os.networkInterfaces();
  for (var devName in interfaces) {
    var iface = interfaces[devName];
    for (var i = 0; i < iface.length; i++) {
      var alias = iface[i];
      if (
        alias.family === "IPv4" &&
        alias.address !== "127.0.0.1" &&
        !alias.internal
      ) {
        return alias.address;
      }
    }
  }
}

// 跨域设置
app.all("*", function (req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Content-Type");
  res.header("Access-Control-Allow-Methods", "*");
  // res.header('Content-Type', 'application/json;charset=utf-8');
  next();
});

app.use(cors({ credentials: true, origin: "http://localhost:8000" }));

app.use("/imgs/", express.static("./uploads/imgs"));

// 加载路由
app.use("/api", require("./routers/api"));

app.use("/install", (req, res) => {
  console.log("管理账号初始化");
  mdb.open("user").then((coll) => {
    coll
      .find({})
      .count()
      .then((count) => {
        if (count === 0) {
          mdb
            .add_user({
              user: "admin",
              password: "admina",
              auth: "admin",
              state: true,
            })
            .then(res.send("管理账号初始化成功！账号：admin 密码：admina"));
        } else {
          res.status(404).send("404 not found");
          console.log("系统已有账号");
        }
      });
  });
});

// APP
app.use("/", express.static("./host"));


io.on("connection", function (socket) {
  console.log("有客户端上线");

  // 监听客户端离线
  socket.on("disconnect", () => {
    console.log("客户端离线");
  });

  socket.on("save_profile", (data) => {
    mdb.save_profile(data).then(socket.emit("ok", "操作完成！"));
  });

  socket.on("get_profile_list", (data) => {
    mdb.find_all(data).then((docs) => {
      socket.emit("profile_list", docs);
    });
  });

  socket.on("get_profile", (data) => {
    mdb.find_one(data).then((doc) => {
      socket.emit("profile", doc);
    });
  });

  socket.on("edit_profile", (data) => {
    mdb.update_one(data).then(socket.emit("ok", "修改成功！"));
  });

  socket.on("login", (data) => {
    mdb.login(data).then((user) => {
      if (user) {
        if (user.state) {
          socket.emit("user", user);
        } else {
          socket.emit("msg", { type: "war", msg: "该账号已被禁用" });
        }
      } else {
        socket.emit("msg", { type: "war", msg: "账号密码错误" });
      }
    });
  });

  socket.on("get_user", () => {
    mdb.get_user().then((docs) => {
      socket.emit("user_list", docs);
    });
  });

  socket.on("edit_user", (data) => {
    mdb.update_user(data).then(socket.emit("ok", "修改成功！"));
  });

  socket.on("add_user", (data) => {
    mdb.add_user(data).then((state) => {
      if (state) {
        socket.emit("ok", "操作完成！");
      } else {
        socket.emit("msg", { type: "war", msg: "已有相同的账号", time: 3 });
      }
    });
  });

  socket.on("delete_user", (query) => {
    mdb.delete_user(query).then(socket.emit("ok", "账号已删除！"));
  });

  socket.on("remove_img", (data)=> {
    mdb.remove_img(data).then(socket.emit("ok", "图片档案已删除！"));
  });

  socket.on("remove_file",data=>{
    mdb.delete(data).then(socket.emit("ok", data.length+"条档案已删除！"))
  })
});

// // 定时任务
// schedule.scheduleJob({ second: [1, 31] }, function () {
//     let oc = io.sockets.server.eio.clientsCount //获取在线人数
//     if (oc !== 0) {
//         let object = new Date()
//         io.sockets.send(object)
//         console.log(object)
//     }
// });
console.log("服务端上线");
console.log(`${getIPAdress()}:3008`);
http.listen(3008, { origins: "*" });
